import React, { Component } from 'react'
import { StyleSheet, View } from 'react-native'
import { inject, observer } from 'mobx-react/native'
import { GiftedChat } from 'react-native-gifted-chat'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'

import { defaultChatName } from '../components'

export const CHAT_QUERY = gql`
  query($id: ID!) {
    Chat(id: $id) {
      id
      name
      members {
        id
        name
      }
      messages(last: 10, orderBy: createdAt_DESC) {
        id
        from {
          id
          name
        }
        content
        createdAt
      }
    }
  }
`

@inject('actions', 'store')
@observer
@graphql(CHAT_QUERY, {
  options: ({ navigation }) => ({
    variables: { id: navigation.getParam('id') },
    fetchPolicy: 'network-only',
  }),
})
@graphql(
  gql`
    mutation($content: String!, $chatId: ID!, $fromId: ID!) {
      createMessage(content: $content, chatId: $chatId, fromId: $fromId) {
        id
        createdAt
      }
    }
  `,
  { name: 'create' },
)
export class ChatScreen extends Component {
  static navigationOptions = ({ navigation }) => ({
    title: navigation.getParam('title', 'Loading..'),
  })

  componentWillReceiveProps({ data, navigation, store }) {
    if (!data.loading && !navigation.getParam('title')) {
      navigation.setParams({ title: defaultChatName(data['Chat'], store.user) })
    }
  }

  send = async messages => {
    await Promise.all(
      messages.map(({ text }) => {
        this.props.create({
          variables: {
            content: text,
            chatId: this.props.data['Chat'].id,
            fromId: this.props.store.user.id,
          },
          // update: async (proxy, response) => {
          //   try {
          //     const message = {
          //       content: text,
          //       from: this.props.store.user,
          //       ...response.data['createMessage'],
          //     }
          //     {
          //       const data = proxy.readQuery({ query: CHAT_QUERY })
          //       data.messages.unshift(message)
          //       store.writeQuery({ query: CHAT_QUERY, data })
          //     }
          //     {
          //       const { CHATS_QUERY } = await import('./chats')
          //       const data = proxy.readQuery({ query: CHATS_QUERY })
          //       const chat = data.user.chats.find(
          //         chat => chat.id === this.props.data['Chat'].id,
          //       )
          //       chat && chat.messages.unshift(message)
          //       store.writeQuery({ query: CHATS_QUERY, data })
          //     }
          //   } catch (error) {
          //     console.error('TODO', error)
          //   }
          // },
        })
      }),
    )
    this.props.data.refetch()
  }

  render = () => (
    <View style={styles.container}>
      <Chat
        data={this.props.data.loading ? {} : this.props.data['Chat']}
        self={this.props.store.user}
        onSend={this.send}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
})

const Chat = ({ data: { messages }, self, onSend }) => (
  <GiftedChat
    messages={toGiftedChatMessages(messages)}
    user={toGiftedChatUser(self)}
    onSend={onSend}
  />
)

const toGiftedChatMessages = messages =>
  messages ? messages.map(toGiftedChatMessage) : []

const toGiftedChatMessage = message => ({
  ...message,
  _id: message.id,
  text: message.content,
  user: toGiftedChatUser(message.from),
})

const toGiftedChatUser = user => ({
  ...user,
  _id: user.id,
})
